<template>
  <div class="app-container">
    <!-- <div id="map"></div> -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="区域名称" prop="regionName">
        <el-input
          v-model="queryParams.regionName"
          placeholder="请输入区域名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="联系电话" prop="phoneNumber">
        <el-input
          v-model="queryParams.phoneNumber"
          placeholder="请输入联系电话"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          v-hasPermi="['business:index:query']"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:index:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:index:del']"
          >批量删除</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <el-table
      v-loading="loading"
      :data="storeList"
      max-height="650px"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column
        label="区域名称"
        align="center"
        :show-overflow-tooltip="true"
        prop="regionName"
        width="120"
      />
      <!-- <el-table-column
        label="区域负责人名称"
        align="center"
        prop="principalName"
      >
        <template slot-scope="scope">
          <span>{{
            scope.row.principalName ? scope.row.principalName : "暂无"
          }}</span>
        </template>
      </el-table-column> -->
      <!-- <el-table-column
        label="会员类型"
        align="center"
        :show-overflow-tooltip="true"
        prop="memberType"
        width="120"
      >
        <template slot-scope="scope">
          <span>{{
            scope.row.memberType == "1" ? "会员价格" : "会员折扣"
          }}</span>
        </template>
      </el-table-column> -->
      <el-table-column
        label="所属区域"
        align="center"
        prop="cityString"
        width="150"
      >
        <template slot-scope="scope">
          <span
            >{{ scope.row.provinceString }}{{ scope.row.cityString
            }}{{ scope.row.countyString }}</span
          >
        </template>
      </el-table-column>
      <!-- <el-table-column label="状态" align="center" prop="regionStatus">
        <template slot-scope="scope">
          <span
            :style="{ color: scope.row.regionStatus ? '#808080' : '#FF5733' }"
            >{{ scope.row.regionStatus == 1 ? "启用" : "禁用" }}</span
          >
        </template>
      </el-table-column> -->
      <el-table-column label="创建人"   align="center"  prop="createBy" />
      <el-table-column label="创建时间"   align="center"  prop="createTime" />
      <el-table-column label="修改人"   align="center"  prop="updateBy" />
      <el-table-column label="修改时间"   align="center"  prop="updateTime" />
      <el-table-column
        label="操作"
        fixed="right"
        align="center"
        class-name="small-padding fixed-width"
        width="250"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:index:edit']"
            >修改</el-button
          >
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-upload2"
            @click="handleGround(scope.row, (regionStatus = 1))"
            v-hasPermi="['business:index:open']"
            :disabled="scope.row.regionStatus === 1"
            >启用</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleGround(scope.row, (regionStatus = 0))"
            :disabled="scope.row.regionStatus === 0"
            v-hasPermi="['business:index:stop']"
            >禁用</el-button
          > -->
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handReset(scope.row)"
            v-hasPermi="['system:store:edit']"
          >重置密码</el-button> -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:index:del']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改门店对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="800px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="区域名称" prop="regionName">
              <el-input
                v-model="form.regionName"
                placeholder="请输入区域名称"
                style="width: 220px"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="省市区" prop="addressAll">
              <el-cascader
                v-model="form.addressAll"
                :options="options"
                @change="handleChange"
                placeholder="请输入省市区"
              ></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row>
          <el-col :span="12">
            <el-form-item label="区域状态" prop="regionStatus">
              <el-select clearable v-model="form.regionStatus">
                <el-option
                  v-for="(item, index) of statusList"
                  :key="index"
                  :label="item.value"
                  :value="item.key"
                  >{{ item.value }}</el-option
                >
              </el-select>
            </el-form-item>
          </el-col>
        </el-row> -->
        <!-- <el-row>
          <el-col :span="12">
            <el-form-item label="会员类型" prop="memberType">
              <el-select clearable v-model="form.memberType">
                <el-option
                  v-for="(item, index) of memberTypeOption"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                  >{{ item.label }}</el-option
                >
              </el-select>
            </el-form-item>
          </el-col>
        </el-row> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listRegion,
  getRegion,
  delRegion,
  addRegion,
  updateRegion,
  listChina,
} from "@/api/system/region";

export default {
  name: "Store",
  data() {
    return {
      // map: null,
      local: null,
      mk: null,
      latitude: "",
      longitude: "",
      keyWords: "",
      result: "",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 门店表格数据
      storeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        storeName: null,
        phoneNumber: null,
        province: null,
        provinceString: null,
        city: null,
        cityString: null,
        county: null,
        countyString: null,
        detail: null,
        longitude: null,
        latitude: null,
        intro: null,
        images: null,
        status: null,
        isInitiate: null,
        openingTime: null,
        closingTime: null,
        regionStatus: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        images: [{ required: true, message: "请选择图片", trigger: "blur" }],
        regionName: [
          { required: true, message: "请输入区域名称", trigger: "blur" },
          {
            min: 1,
            max: 10,
            message: "长度在 1 到 10 个字符",
            trigger: "blur",
          },
        ],
        phoneNumber: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "手机号码格式不正确",
            trigger: "blur",
          },
        ],
        openingTime: [
          { required: true, message: "请选择营业时间", trigger: "blur" },
        ],
        memberType: [
          { required: true, message: "请选择会员类型", trigger: "blur" },
        ],
        isInitiate: [
          { required: true, message: "请选择是否营业", trigger: "blur" },
        ],
        addressAll: [
          { required: true, message: "请选择省市区", trigger: "blur" },
        ],
        regionId: [
          { required: true, message: "请选择所属区域", trigger: "blur" },
        ],
        detail: [
          { required: true, message: "请选择详细地址", trigger: "blur" },
          {
            min: 1,
            max: 30,
            message: "长度在 1 到 30 个字符",
            trigger: "blur",
          },
        ],
        intro: [
          { required: true, message: "请选择简介", trigger: "blur" },
          {
            min: 1,
            max: 30,
            message: "长度在 1 到 30 个字符",
            trigger: "blur",
          },
        ],
      },
      options: [],
      List: [
        {
          key: 1,
          value: "营业中",
        },
        {
          key: 2,
          value: "未营业",
        },
      ],
      favourable: [
        {
          key: 1,
          value: "优惠价",
        },
        {
          key: 2,
          value: "折扣价",
        },
      ],
      statusList: [
        {
          key: 1,
          value: "启用",
        },
        {
          key: 0,
          value: "禁用",
        },
      ],
      region: [],
      memberTypeOption: [
        { label: "会员价", value: 1 },
        { label: "会员折扣", value: 2 },
      ],
    };
  },
  created() {
    this.getList();
    this.listChina();
  },
  mounted() {
    // this.initMap();
  },
  methods: {
    changeRegion(value) {
      const selectedOption = this.region.find((item) => item.key === value);
      const selectedKey = selectedOption.key;
      const selectedValue = selectedOption.value;
      console.log(`Selected Key: ${selectedKey}`);
      console.log(`Selected Value: ${selectedValue}`);
      this.form.regionName = selectedValue;
      console.log(this.form.regionName, 444);
    },
    // initMap() {
    //   this.map = new BMap.Map("map");
    //   let point = new BMap.Point(116.404, 39.915);
    //   this.map.centerAndZoom(point, 12);
    //   this.map.enableScrollWheelZoom(true); // 开启鼠标滚轮缩放
    //   this.map.addControl(new BMap.NavigationControl());
    // },
    // 点击定位-定位到当前位置
    // fixedPos() {
    //   const _this = this;
    //   const geolocation = new BMap.Geolocation();
    //   this.confirmLoading = true;
    //   geolocation.getCurrentPosition(function (r) {
    //     if (this.getStatus() == BMAP_STATUS_SUCCESS) {
    //       _this.handleMarker(_this, r.point);
    //       let myGeo = new BMap.Geocoder();
    //       myGeo.getLocation(
    //         new BMap.Point(r.point.lng, r.point.lat),
    //         function (result) {
    //           _this.confirmLoading = false;
    //           if (result) {
    //             _this.latitude = result.point.lat;
    //             _this.longitude = result.point.lng;
    //           }
    //         }
    //       );
    //     } else {
    //       _this.$message.error("failed" + this.getStatus());
    //     }
    //   });
    // },
    // 搜索地址
    // setPlace() {
    //   this.local = new BMap.LocalSearch(this.map, {
    //     onSearchComplete: this.searchPlace,
    //   });
    //   this.local.search(this.form.detail);
    // },
    // searchPlace() {
    //   if (this.local.getResults() != undefined) {
    //     this.map.clearOverlays(); //清除地图上所有覆盖物
    //     if (this.local.getResults().getPoi(0)) {
    //       let point = this.local.getResults().getPoi(0).point; //获取第一个智能搜索的结果
    //       this.map.centerAndZoom(point, 18);
    //       this.handleMarker(this, point);
    //       console.log("经度：" + point.lng + "--" + "纬度" + point.lat);
    //       this.form.longitude = point.lng;
    //       this.form.latitude = point.lat;
    //       this.latitude = point.lat;
    //       this.longitude = point.lng;
    //     } else {
    //       this.$message.error("未匹配到地点!");
    //     }
    //   } else {
    //     this.$message.error("未找到搜索结果!");
    //   }
    // },
    // 设置标注
    // handleMarker(obj, point) {
    //   obj.mk = new BMap.Marker(point);
    //   obj.map.addOverlay(obj.mk);
    //   obj.mk.enableDragging(); // 可拖拽
    //   obj.mk.addEventListener("dragend", function (e) {
    //     // 监听标注的拖拽，获取拖拽后的经纬度
    //     this.latitude = point.lat;
    //     this.longitude = point.lng;
    //   });
    //   obj.map.panTo(point);
    // },
    listChina() {
      listChina().then((res) => {
        console.log(res, 123);
        this.options = res.data.map((rItem) => {
          return {
            value: rItem.id,
            label: rItem.cityName,
            children: rItem.children.map((item) => {
              return {
                value: item.id,
                label: item.cityName,
                children: item.children.map((stem) => {
                  return {
                    value: stem.id,
                    label: stem.cityName,
                  };
                }),
              };
            }),
          };
        });
      });
    },
    handleChange() {
      console.log(this.form.province, 123);
    },
    // blurDetail() {
    //   const geocoder = new BMap.Geocoder();
    //   console.log(geocoder);
    //   geocoder.getPoint(
    //     this.form.detail,
    //     (point) => {
    //       if (point) {
    //         this.result = `经度：${point.lng}，纬度：${point.lat}`;
    //         console.log(this.result, 123);
    //       } else {
    //         this.result = "地址解析失败";
    //         console.log(this.result, 123);
    //       }
    //     },
    //     "北京市"
    //   );
    // },
    /** 查询门店列表 */
    getList() {
      this.loading = true;
      listRegion(this.queryParams).then((response) => {
        this.storeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        storeName: null,
        phoneNumber: null,
        province: null,
        provinceString: null,
        city: null,
        cityString: null,
        county: null,
        countyString: null,
        detail: null,
        longitude: null,
        latitude: null,
        intro: null,
        images: null,
        status: null,
        isInitiate: null,
        openingTime: null,
        closingTime: null,
        createTime: null,
        updateTime: null,
        regionStatus: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加区域";
      this.form.memberType = 2;
    },
    handleGround(row, regionStatus) {
      const params = {
        id: row.id,
        regionStatus: regionStatus,
      };
      this.$confirm(
        `此操作将${regionStatus === 1 ? "启用" : "禁用"}该数据, 是否继续?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          updateRegion(params).then((res) => {
            this.$message({
              type: "success",
              message: `${regionStatus === 1 ? "启用" : "禁用"}成功!`,
            });
            this.getList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消启用/禁用",
          });
        });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getRegion(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改区域";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateRegion(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRegion(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // handReset(row) {
    //   const ids = row.id || this.ids;
    //   const storeName=row.storeName
    //   this.$modal.confirm('是否确认重置区域名称为"' + storeName + '"的数据项？').then(function() {
    //     return listResetPwd({userId:ids});
    //   }).then(() => {
    //     this.getList();
    //     this.$modal.msgSuccess("重置成功");
    //   }).catch(() => {});
    // },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除区域名称为"' + ids + '"的数据项？')
        .then(function () {
          return delRegion(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/store/export",
        {
          ...this.queryParams,
        },
        `store_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style>
.el-dialog__footer {
  text-align: center;
}
</style>
